package com.googlecode.continuity.plugin.project.server.rpc;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.acegisecurity.context.SecurityContextHolder;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.googlecode.continuity.core.client.Group;
import com.googlecode.continuity.core.server.security.SecurityUserToken;
import com.googlecode.continuity.plugin.project.client.Milestone;
import com.googlecode.continuity.plugin.project.client.MilestoneSuggestion;
import com.googlecode.continuity.plugin.project.client.Project;
import com.googlecode.continuity.plugin.project.client.ProjectRPC;
import com.googlecode.continuity.plugin.project.server.service.ProjectService;
import com.googlecode.continuity.plugin.svnbrowser.client.ReadSVNException;
import com.googlecode.continuity.plugin.svnbrowser.client.SVNRepositoryHandle;
import com.googlecode.continuity.plugin.svnbrowser.server.service.ReadSVNService;

/**
 * ProjectRPCImpl
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class ProjectRPCImpl implements ProjectRPC {
// ------------------------------ FIELDS ------------------------------

  private ProjectService projectService;
  private ReadSVNService svnService;

// --------------------- GETTER / SETTER METHODS ---------------------

  public void setProjectService(ProjectService projectService) {
    this.projectService = projectService;
  }

  public void setSvnService(ReadSVNService svnService) {
    this.svnService = svnService;
  }

// ------------------------ INTERFACE METHODS ------------------------

// --------------------- Interface ProjectRPC ---------------------

  public void storeProject(Project project) {
    projectService.storeProject(project);
  }

  public void createProject(Project project) {
    Group members = new Group();
    members.setName(project.getName());
    members.addMember(
        ((SecurityUserToken) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser());
    project.setMembers(members);
    projectService.storeProject(project);
  }

  public Project getProjectById(int id) {
    return projectService.getProjectByID(id);
  }

  public SVNRepositoryHandle getRepositoryHandle(int projectID) throws ReadSVNException {
    // TODO: add username and password AND don't share them down the wire
    return svnService.connect(projectService.getProjectByID(projectID).getRepositoryLocation(), "", "");
  }

  public List findMilestones(String search) {
    return projectService.findMilestones(search);
  }

  public void addMilestone(int projectID, int milestoneID) {
    Project project = projectService.getProjectByID(projectID);
    project.addMilestone(projectService.getMilestoneByID(milestoneID));
    projectService.storeProject(project);
  }
}
